<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 2017/7/27
 * Time: 下午6:47
 */

namespace app\models;

use app\librarys\DbCacheUtility;

/**
 * 系统功能点
 * Class Manager
 * @package app\models
 */
class FunctionPoint
{
    public static function getList()
    {
        $cmd = \Yii::$app->db->createCommand("SELECT * FROM t_function_point WHERE id='0'");
        $result = DbCacheUtility::queryOne($cmd);
        if ($result == false) {
            return [];
        }
        $result['level'] = 0;

        $items = [];
        array_push($items, $result);

        $children = self::_getChildrenList('0', 1);
        if (count($children) > 0) {
            foreach ($children as $child) {
                array_push($items, $child);
            }
        }

        return $items;
    }

    private static function _getChildrenList($parentId, $level)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM t_function_point WHERE parent_id=:parentId');
        $cmd->bindValue(':parentId', $parentId);
        $resultList = DbCacheUtility::queryAll($cmd);

        $items = [];

        if (count($resultList) > 0) {
            foreach ($resultList as $result) {
                $result['level'] = $level;
                array_push($items, $result);

                $children = self::_getChildrenList($result['id'], $level + 1);
                if (count($children) > 0) {
                    foreach ($children as $child) {
                        array_push($items, $child);
                    }
                }
            }
        }
        return $items;
    }

    public static function get($id)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM v_function_point WHERE id=:id');
        $cmd->bindValue(':id', $id);
        $item = $cmd->queryOne();
        if ($item == false) {
            return null;
        } else {
            return $item;
        }
    }

    /**
     * 新增、修改
     * @param mixed $data 如果$data['id']=='' 则新增
     * @return int
     * @throws \yii\db\Exception
     */
    public static function add($data)
    {
        $cmd = \Yii::$app->db->createCommand('call p_add_function_point(:in_id, :in_name, :in_description, :in_controller_id, :in_action_id, :in_parent_id)');
        $cmd->bindValue(':in_id', $data['id']);
        $cmd->bindValue(':in_name', $data['name']);
        $cmd->bindValue(':in_description', $data['description']);
        $cmd->bindValue(':in_controller_id', $data['controller_id']);
        $cmd->bindValue(':in_action_id', $data['action_id']);
        $cmd->bindValue(':in_parent_id', $data['parent_id']);
        return $cmd->execute();
    }

    public static function delete($functionPointId)
    {
        $cmd = \Yii::$app->db->createCommand('call p_delete_function_point(:in_function_point_id)');
        $cmd->bindValue(':in_function_point_id', $functionPointId);
        return $cmd->execute();
    }
}